<?php

/**

 * Created by PhpStorm.

 * User: Administrator

 * Date: 2018/11/19

 * Time: 16:51



 * 订单类

 */



namespace app\console\controller;

use app\console\model\ServiceOrderGoods;

use think\Build;

use think\Controller;

use think\Db;

use think\Request;

use think\Url;

use think\Session;

use app\interfaces\controller\Alipay;

use think\Exception;

use app\console\model\RefundOrderAudit;

use app\common\trilateral\Classify as ClassifyAlias;

use think\Cache;

class GiftOrder extends Controller

{

    /**

     * @return array|mixed|\think\response\View

     * 订单列表

     */

    public function index()

    {

        $param = Request::instance()->param();
			
        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10

        $where['o.order_type'] = ['eq', 3];

        $where['o.status'] = ['in','1,6,5,4,10,11,12,20'];

        $auding_status = Session::get('auding_status');

        if($auding_status == 1){

           // $where['shop_id'] = ['eq',Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id')];

            //$where['o.auding_status'] = ['eq',2];

        }

        if (!empty($param['status'])){

            if($param['status'] == 2){

                $where['o.status'] = ['in', $this->status];

            }else{
				if($param['status']=='12'){
					//$where['o.status'] = ['eq', '5'];
					$where['o.tui_status']=['eq','2'];
				}else{
					$where['o.status'] = ['eq', $param['status']];	
				}
                

            }

        }

        if (!empty($param['auding_status'])){

            $where['o.auding_status'] = ['eq', $param['auding_status']];

            $where['o.is_free_order'] = ['eq', 2];

        }

        if (!empty($param['card_type'])) $where['o.card_type'] = ['eq', $param['card_type']];

        if (!empty($param['finance_order'])) $where['o.finance_order'] = ['eq', $param['finance_order']];

        if (!empty($param['order_online'])) $where['o.order_online'] = ['eq', $param['order_online']];

        if (!empty($param['is_certification'])) $where['m.is_certification'] = ['eq', $param['is_certification']];

        if (!empty($param['order_type'])) $where['o.order_type'] = ['eq', $param['order_type']];

        if (!empty($param['shop_id'])){

//             $where['m.shop_invite_id|o.shop_id'] = ['eq', $param['shop_id']];  2020-6-11修改

             $where['o.shop_id'] = ['eq', $param['shop_id']];

        }

        if (!empty($param['gift_id'])) $where['o.gift_id'] = ['eq', $param['gift_id']];



        if (!empty($param['title'])) $where['o.username|o.shop_order_number|o.order_number|m.car_number|o.car_number|o.gift_title|o.card_num'] = ['like', '%'.$param['title'].'%'];

        if (!empty($param['interval_timer'])) {

            $interval_timer = explode('/', $param['interval_timer']);

            $where['o.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];

        }else{
			$six_begin_time = date('Y-m-d 00:00:00',time());
			$six_end_time = date('Y-m-d 23:59:59',time());
			$where['o.create_time'] = ['between', [$six_begin_time, $six_end_time]];
		}

        if(session('role_id') != 1){

            $where['o.is_delete'] = ['eq', 1];

        }
        $data = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

            ->join('gift_card gc','o.id = gc.order_id','left')

            ->field('m.username,m.is_certification,m.car_model,m.car_number m_car_number,o.*,s.shop_title,gc.card_num')//,gc.card_num

            ->where($where)

            ->order('id','desc')

            ->paginate(10, false, ['query' => $param])->each(function($item,$key) use ($level){





                $item->m_car_number = (new \app\index\controller\GiftOrder())->car_number('',$item->member_id);

                $item->message = 1;//默认没有未读消息

                $gift_news = Db::name('gift_news')->where('order_id', $item->id)->where('manage_id',session('manage_id'))->find();

                if(empty($gift_news)){ //包含有未读消息

                    $item->message = 2;

                }

                if(session('role_id') != 1){

                    $item->username = hideStr($item->username,1,6);

                }

                if($item['status'] == 10 || $item['status'] == 11){
                    $item->refund_create_time = Db::name('order_refund')->where('order_id',$item['id'])->value('create_time');
                }

                if($item->is_certification == 2 && !empty($item->car_number)){

                    //$item->car_number = '('.$item->car_number.')';

                }

                if($item->t_type == 2){

                    $item->gift_title = '(会员卡)'.$item->mc_title;

                }

                $item->refund_button = false;

                $count = (new RefundOrderAudit())->where('order_id',$item->id)->where('status','11')->count();



                if($level == 7){

                    if($count == 0){

                        $item->refund_button = true;

                    }

                }

                if($level == 8){

                    if($count == 1){

                        $item->refund_button = true;

                    }

                }

                if($level == 9){

                    if($count == 2){

                        $item->refund_button = true;

                    }

                }

                if($level == 10){

                    if($count == 3){

                        $item->refund_button = true;

                    }

                }



            });

        $total_count = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

            ->join('gift_card gc','o.id = gc.order_id','left')

            ->field('o.*,m.username,s.shop_title')

            ->where($where)->count();

        $total_price = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('gift_card gc','o.id = gc.order_id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

            ->field('o.*,m.username,s.shop_title')

            ->where($where)->sum('amount');

        $shop_list = Db::name('shop s')->field('id,shop_title')->select();

        $gift_list = (new \app\console\model\Order())->alias('o')->join('gift g', 'o.gift_id = g.id','left')->group('g.id')->select();



        return view('', ['data' => $data,

            'shop_list' => $shop_list,

            'total_count' => $total_count,

            'total_price' => $total_price,

            'gift_list' => $gift_list,

        ]);

    }







    public function delete($id)

    {

        //Db::name('member_message')->where('order_number','in','10728,10729,10730')->delete(); //	,, //10730

        //halt(1);

            //礼包记录ID

        $order_id = Db::name('shop_assignor_records')->where('id', $id)->value('order_id');

        $shop_id = Db::name('shop_assignor_records')->where('id', $id)->value('shop_id');

        $create_time = Db::name('shop_assignor_records')->where('id', $id)->value('create_time');

        $select = Db::name('shop_assignor_records sar')

            ->where('order_id', $order_id)

            ->where('shop_id', $shop_id)

            ->where('sar.create_time', $create_time)

            ->join('single s','sar.assignor_content = s.id','left')



            ->where('assignor_content','neq',9999)

            ->column('sar.id');



        $pub_id = Db::name('shop_assignor_records sar')

            ->where('order_id', $order_id)

            ->where('shop_id', $shop_id)

            ->where('sar.create_time', $create_time)

            ->join('single s','sar.assignor_content = s.id','left')



            ->where('assignor_content','neq',9999)

            ->value('pub_id');//删除过的 全数据保存的那个
			$content_a = '';
			$shop_assignor_records_type =Db::name('shop_assignor_records')->where('id', $id)->value('type');
			$shop_assignor_records_assignor_price =Db::name('shop_assignor_records')->where('id', $id)->value('assignor_price');
			$shop_assignor_records_assignor_id=Db::name('shop_assignor_records')->where('id', $id)->value('assignor_id');
			$shop_assignor_records_assignor_content=Db::name('shop_assignor_records')->where('id', $id)->value('assignor_content');
			$shop_assignor_records_single_id=Db::name('shop_assignor_records')->where('id', $id)->value('single_id');
			$shop_assignor_records_order_type=Db::name('shop_assignor_records')->where('id', $id)->value('order_type');
			$shop_assignor_records_type=Db::name('shop_assignor_records')->where('id', $id)->value('type');
			//新增日志
					//根据类型判断是服务提成还是销售提成
					if($shop_assignor_records_type=='1'){
						$content_a =$content_a.'提成类型:服务提成'; 
					}elseif($shop_assignor_records_type=='2'){
						$content_a =$content_a.'提成类型：售卖提成'; 
					}
					///服务门店
					$shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');
					$order_num_a = Db::name('order')->where('id',$order_id)->value('order_number');
					$content_a = $content_a."--门店名称:".$shop_title;
					//查询提交的这个信息
					$content_a = $content_a."--提成金额：".$shop_assignor_records_assignor_price;
					$content_a=$content_a."--服务人员：".Db::name('shop_assignor')->where('id',$shop_assignor_records_assignor_id)->value('name');
					if($shop_assignor_records_order_type =='3'){
						$content_a=$content_a."--服务内容：".Db::name('single')->where('id',$shop_assignor_records_assignor_content)->value('cat_name');
					}else{
						$content_a=$content_a."--服务内容：".Db::name('shop_goods')->where('id',$shop_assignor_records_single_id)->value('title');
					}
					$insert_log =  Db::name('member_log')->insert(
					 ['type_status' => 1,
					 'member_name' => \session('manage_user'),
					 'content' => $content_a,
					 'add_time' => time(),
					 'add_time_date'=> date('Y-m-d H:i:s',time()),
					 'type' => 3,
					 'member_id' => \session('manage_id'),
					 'member_jibie' => \session('manage_nick'),
					 'order_id' => $order_id,
					 'order_num' => $order_num_a,
					 'order_type'=>$shop_assignor_records_type,
					]);
					
					
					//新增日志		
		

        $count = count($select);

        if($count >1){ //数量多于1条的时候给修改保存上



            if(empty($pub_id)){  //空的时候添加 不空的时候不用管 就是只负责第一次

                Db::name('shop_assignor_records sar')

                    ->where('order_id', $order_id)

                    ->where('shop_id', $shop_id)

                    ->where('sar.create_time', $create_time)

                    ->join('single s','sar.assignor_content = s.id','left')



                    ->where('assignor_content','neq',9999)

                    ->setField('pub_id',implode(',',$select));

            }



        }

        if($count == 1){

            Db::name('member_message')->where('order_number','in',$pub_id)->delete();

        }

        $ret = Db::name('shop_assignor_records')->where('id', $id)->delete();

        if(empty($select)){

            //

        }

        if ($ret) {

            return ['code' => 200, 'message' => '删除成功'];

        }

        return ['code' => 400, 'message' => '失败'];

    }





    public function iii(){

        $j = 0;

        ++$j;

        return $j;

    }



    /**

     * @param $id

     * 订单修改

     * 6已完成

     */

    public function update($id)

    {

        //\session('manage_id',14);

//        if (Request::instance()->isPost()) {

//            try {

//                wingo('haha','134');

//            } catch (\Exception $e) {

//                halt($e->getMessage());

//            }

//

//        }



        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10



        $param = Request::instance()->param();



        $find = Db::name('order')->find($id);

        $auding_status = Session::get('auding_status');

        if($auding_status == 2){

            Db::name('order o')->where('id',$id)->setField('is_read',1);

        }else{

            Db::name('order o')->where('id',$id)->setField('is_read_shop',1);

        }

        //礼包消息读取

        $gift_news = Db::name('gift_news')->where('order_id', $id)->where('manage_id',session('manage_id'))->find();

        if(empty($gift_news)){ //如果没有就添加 如果有不处理

            Db::name('gift_news')->insert(['order_id' => $id,'manage_id' => session('manage_id')]);

        }

        $refund = Db::name('order_refund ors')->field('ors.*,rr.title')->where('order_id',$find['id'])->join('refund_reason rr','ors.reason_id = rr.id')->find();

        if (Request::instance()->isPost()) {

            $car_number = Request::instance()->post('car_number');

            if(isset($car_number) && empty($car_number)){

                fail('必须填写车牌号');

            }

            $status = Db::name('order')->where('id',$id)->value('status');

            $gift_end_time = Db::name('order')->where('id',$id)->value('gift_end_time');

            if(($gift_end_time) < date('Y-m-d H:i:s',time())){

                //fail('礼包已经过期,不能再添加服务');

            }



            if ($status == 6) {

                $shop_assignor_records = [];

                if(empty($param['assignor_id'])){

                    //fail('请添加门店人员');

                }

                if(empty($param['shop_id'])){

                  //  fail('门店人员必须添加');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(!empty($param['assignor_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }

                Db::startTrans();

                try {

                    if (!empty($param['spec_id']) && !empty($param['number'])) { //服务商品



                        for ($i = 0; $i < count($param['spec_id']); $i++) {

                            $auding_status = Session::get('auding_status');

                            if ($auding_status == 1) {

                                $shop_id = \session('shop_id');

                            } else {

                                $shop_id = Request::instance()->param()['shop_id'][$i];

                            }



                            (new ServiceOrderGoods())->save([

                                'shop_id' => $shop_id,

                                'order_id' => $find['id'],

                                'cat_id' => $param['cat_id'][$i],

                                'spec_id' => $param['spec_id'][$i],

                                'number' => $param['number'][$i],

                                'create_time' => date('Y-m-d H:i:s', time())

                            ]);

                            $inventory = Db::name('shop_spec_attr')->where('id', $param['spec_id'][$i])->setDec('inventory', $param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                        }

                        //(new ServiceOrderGoods())->saveAll($service_order_goods);

                    }

                    if (!empty($param['assignor_id'])) {



                        //$single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

                        $single_title = Db::name('single')->where('id', $param['single_id'][0])->value('cat_name');

                        //$assignor_price = explode('-',$param['single_id'][0])[1];//门店金额
						$content_a = '';
                        $new_array = [];
						
                        for ($i = 0; $i < count($param['assignor_id']); $i++) {

                            $auding_status = Session::get('auding_status');

                            if ($auding_status == 1) {

                                $shop_id = \session('shop_id');

                            } else {

                                $shop_id = Request::instance()->param()['shop_id'][$i];

                            }

                            //                        $shop_assignor_records[$i]['order_id'] = $find['id'];

                            //                        $shop_assignor_records[$i]['shop_id'] = $shop_id;

                            //                        $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                            //                        $shop_assignor_records[$i]['single_id'] = $single_id;

                            //                        $shop_assignor_records[$i]['assignor_price'] = $assignor_price;

                            //                        $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                            //                        $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                            //                        $shop_assignor_records[$i]['order_type'] = $find['order_type'];
							/*****************************************/
							//查询GIFid
							$gift_id_a = Db::name('order')->where('id', $find['id'])->value('gift_id');
							
							
							if($param['typea'][$i]=='1'){
								if($param['post_id'][$i] !=''){
									//查询岗位百分比
									$ticheng  = Db::name('post_list')->where('post_id', $param['post_id'][$i])->where('cat_id', $param['assignor_content'][$i])->where('shop_id', $shop_id)->order('id', 'desc')->limit('0,1')->value('post_num');
								}else{
									$ticheng = '0';
								}
								$person_price1 = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $param['assignor_content'][$i])->count();
								if($person_price1=='0'){
									$person_price ='0'; 
									$price ='0'; 
								}else{
									$person_price = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $param['assignor_content'][$i])->value('person_price');  
									$price = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $param['assignor_content'][$i])->value('price');  
								}
								//计算总提成
								$assignor_price = $ticheng + $person_price;
								$param['assignor_price'][$i] = $assignor_price;
							}elseif($param['typea'][$i]=='2'){
								//根据order_id查询出这个订单的销售提成
								if($param['post_id'][$i] !=''){
									//查询岗位百分比
									//$ticheng  = Db::name('goods_gangwei')->where('post_id', $param['post_id'][$i])->where('goods_id', $assignor_content)->order('id', 'desc')->limit('0,1')->value('post_fuwu');
									$ticheng  = Db::name('gift_gangwei')->where('post_id', $param['post_id'][$i])->where('gift_id',$gift_id_a )->order('id', 'desc')->limit('0,1')->value('post_xiaoshou');
									//$ticheng = '0';
								}else{
									$ticheng = '0';
								}
								$gift_id = Db::name('order')->where('id', $find['id'])->value('gift_id');
								//礼包销售提成
								$person_price1 = Db::name('gift_shop_price')->where('shop_id', $shop_id)->where('gift_id', $gift_id)->count();
								if($person_price1=='0'){
									$person_price ='0';  
								}else{
									$person_price = Db::name('gift_shop_price')->where('shop_id', $shop_id)->where('gift_id', $gift_id)->value('price');   
								}
								//计算总提成
								$assignor_price = $ticheng + $person_price;
								$param['assignor_price'][$i] = $assignor_price;
							}else{
								
							
							}
							/*******************************/
                            $is_agree = 1;

                            if ($param['single_id'][$i] == 9999) {

                                $is_agree = 2;

                            }



                            $shop_assignor_records_id = Db::name('shop_assignor_records')->insertGetId(

                                ['assignor_id' => $param['assignor_id'][$i],

                                    'assignor_price' => $param['assignor_price'][$i],
									'post_id' => $param['post_id'][$i],
                                    'single_id' => $param['single_id'][$i],
									'pici'=> $param['pici'][$i],
                                    'order_id' => $find['id'],
									'type' => $param['typea'][$i],
                                    'order_type' => $find['order_type'],

                                    'is_agree' => $is_agree,

                                    'assignor_content' => $param['assignor_content'][$i],

                                    'create_time' => date('Y-m-d H:i:s', time()),

                                    'shop_id' => $shop_id

                                ]);
							//新增日志
							//根据类型判断是服务提成还是销售提成
							if($param['typea'][$i]=='1'){
								$content_a =$content_a.'提成类型:服务提成'; 
							}elseif($param['typea'][$i]=='2'){
								$content_a =$content_a.'提成类型：售卖提成'; 
							}
							///服务门店
							$shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');
							$order_num_a = Db::name('order')->where('id',$find['id'])->value('order_number');
							$content_a = $content_a."--门店名称:".$shop_title;
							//查询提交的这个信息
							$content_a = $content_a."--提成金额：".$param['assignor_price'][$i];
							$content_a=$content_a."--服务人员：".Db::name('shop_assignor')->where('id',$param['assignor_id'][$i])->value('name');
							$content_a=$content_a."--消费日期：".date('Y-m-d H:i:s',time());
							$content_a=$content_a."--服务内容：".Db::name('single')->where('id',$param['assignor_content'][$i])->value('cat_name');
							$insert_log =  Db::name('member_log')->insert(
							 ['type_status' => 3,
							 'member_name' => \session('manage_user'),
							 'content' => $content_a,
							 'add_time' => time(),
							 'add_time_date'=> date('Y-m-d H:i:s',time()),
							 'type' => 1,
							 'member_id' => \session('manage_id'),
							 'member_jibie' => \session('manage_nick'),
							 'order_id' => $find['id'],
							 'order_num' => $order_num_a,
							 'order_type'=>$param['typea'][$i],
							]);
							$content_a = '';
                            $new_array[] = $shop_assignor_records_id;

                            Db::name('member_message')->insert(

                                ['member_id' => $find['member_id'],

                                    'order_number' => $shop_assignor_records_id,

                                    'type_id' => 4,

                                    'title' => $find['gift_title'] . '礼包已设置,请确认使用',

                                    'content' => '服务类型:' . $single_title,

                                    'is_click' => 1,

                                    'create_time' => date('Y-m-d H:i:s', time())

                                ]);



                        }

                        $order = DB::name('shop_assignor_records')->group('create_time')->where('id', 'in', $new_array)->order('id', 'desc')->select()->toArray(); //查询未同意的所有订单数据



                        foreach ($order as $k => &$v) {

                            $v['create_time_list'] = DB::name('shop_assignor_records')->group('assignor_content')->where('create_time', $v['create_time'])->select()->toArray();

                        } //得到当前同一时间段 不用服务内容的唯一类;



                        foreach ($order as $v1) {

                            foreach ($v1['create_time_list'] as $v2) {



                                if ($v2['assignor_content'] != "9999") {


									/**********************************************
                                    $g_ret = Db::name('order_gift_count')

                                        ->where('order_id', $v2['order_id'])

                                        ->where('single_content', $v2['assignor_content'])

                                        ->setDec('gift_count', 1);//订单礼包次数
									*********************************************/
									/************************/
									$insert_log_libao =  Db::name('libao_log')->insert(
									 [
									 'member_name' => \session('manage_user'),
									 'content' => $content_a,
									 'add_time' => time(),
									 'add_time_date'=> date('Y-m-d H:i:s',time()),
									 'member_id' => \session('manage_id'),
									 'order_id' => $v2['order_id'],
									 'single_content' => $v2['assignor_content'],
									 'shifou_zengjia' => '0',
									]);	
									//防止重复扣次数
									//先查询这个订单这个分类的是零的有没有
									$shifou_kou_cishu = 
									DB::name('libao_log')
									->where('order_id', $v2['order_id'])
									->where('member_id', \session('manage_id'))
									->where('single_content', $v2['assignor_content'])
									->where('shifou_zengjia', 0)
									->count();
									
									if($shifou_kou_cishu > '0'){
									//扣次数日志
									$g_ret = Db::name('order_gift_count')
									    ->where('order_id', $v2['order_id'])
									    ->where('single_content', $v2['assignor_content'])
									    ->setDec('gift_count', 1);//订单礼包次数	
									//扣完次数，把所有的0都改成1
									$aaaa = Db::name('libao_log')
											->where('order_id', $v2['order_id'])
											->where('member_id', \session('manage_id'))
											->where('single_content', $v2['assignor_content'])
											->where('shifou_zengjia', 0)
											->update(['shifou_zengjia' => 1]);	
									}	
									/************************/
                                    if (!$g_ret) { //就是失败 $g_ret != true

                                        // abort(404);



                                        return json_encode(['code' => 200, 'message' => $v1['id']]);

                                        //throw new \think\Exception($v2['id'], 500);

                                    }

                                }



                            }



                        }



                        //Db::name('order_gift_count')->where('order_id',$id)->where('single_id',$single_id)->setDec('gift_count');//礼包剩余次数减少

                        (new \app\index\controller\MemberMessage())->jpushMessage($find['member_id'], $find['gift_title'] . '礼包已设置,请确认使用', '服务类型:' . $single_title, 4);



                        //Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                    }

                    Db::name('order')->where('id',$id)->where('status',6)->update(['status' => 5]);

                    Db::name('order')->where('id',$id)->where('status',6)->update(['explain' => $param['explain']]);

                    Db::commit();

                } catch (Exception $e) {

                    Db::rollback();

                }

                if(empty($param['assignor_id'])){ //如果没有添加人员就是 普通的修改数据

                    //fail('请添加门店人员');

                    Db::name('order')->where('id',$id)->update(['explain' => $param['explain']]);

                    wingo('修改成功', Url::build('index'));

                }else{



                    wingo('2门店人员分配完毕', Url::build('index'));

                }

//                   Db::name('order')->where('id',$id)->where('status',6)->update(['status' => 5]);

//                wingo('门店人员分配完毕', Url::build('index'));



            }

            if ($status == 5 || $status == 4) {

                $shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;

                //if(empty($shop_id)) fail('当前管理员不是门店管理员');

                if(empty($param['assignor_id'])){

                    fail('请添加门店人员');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }

                if(isset($param['shop_id']) &&  count(array_unique($param['shop_id'])) >= 2){

                    //fail('一次只能服务一个门店');

                }

                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                    $service_order_goods = [];

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        $auding_status = Session::get('auding_status');

                        if($auding_status == 1){

                            $shop_id =  \session('shop_id');

                        }else{

                            $shop_id = Request::instance()->param()['shop_id'][$i];

                        }

                                        //服务商品

                        (new ServiceOrderGoods())->save([

                            'shop_id' => $shop_id,

                            'order_id' => $find['id'],

                            'cat_id' => $param['cat_id'][$i],

                            'spec_id' => $param['spec_id'][$i],

                            'number' => $param['number'][$i],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                    }

                    //(new ServiceOrderGoods())->saveAll($service_order_goods);

                }

                Db::startTrans();

                try {

                    if (!empty($param['assignor_id'])) {

                        Db::name('order')->where('id',$id)->update(['explain' => $param['explain']]);
						//var_dump($param['assignor_id']);
                        //$single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了



                        //$assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                        $single_title = '';

                        $new_array = [];
						$content_a = '';
                        for ($i = 0; $i < count($param['assignor_id']); $i++) {
                            $single_array[] = Db::name('single')->where('id', $param['assignor_content'][$i])->value('cat_name');

                            $auding_status = Session::get('auding_status');

                            if ($auding_status == 1) {

                                $shop_id = \session('shop_id');

                            } else {

                                $shop_id = Request::instance()->param()['shop_id'][$i];

                            }
							//查询选择的岗位是不是这个门店
							/*if($param['post_id'][$i] !=''){
								$gangwei_status = Db::name('job')->where('id', $param['post_id'][$i])->value('shop_id');
								if($gangwei_status != $shop_id){
									 fail('清选择门店对应的岗位');
								}
							}*/
							//
							$gift_id_a = Db::name('order')->where('id', $find['id'])->value('gift_id');
							/*****************************************/
							if($param['typea'][$i]=='1'){
								if($param['post_id'][$i] !=''){
									//查询岗位百分比
									$ticheng  = Db::name('post_list')->where('post_id', $param['post_id'][$i])->where('cat_id', $param['assignor_content'][$i])->where('shop_id', $shop_id)->order('id', 'desc')->limit('0,1')->value('post_num');
								}else{
									$ticheng = '0';
								}
								$person_price1 = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $param['assignor_content'][$i])->count();
								if($person_price1=='0'){
									$person_price ='0'; 
									$price ='0'; 
								}else{
									$person_price = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $param['assignor_content'][$i])->value('person_price');  
									$price = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $param['assignor_content'][$i])->value('price');  
								}
								//计算总提成
								$assignor_price = $ticheng + $person_price;
								$param['assignor_price'][$i] = $assignor_price;
							}elseif($param['typea'][$i]=='2'){
								//根据order_id查询出这个订单的销售提成
								if($param['post_id'][$i] !=''){
									//查询岗位百分比
									//$ticheng  = Db::name('post_list')->where('post_id', $param['post_id'][$i])->where('shop_id', $shop_id)->order('id', 'desc')->limit('0,1')->value('post_num_xiaoshou');
									$ticheng  = Db::name('gift_gangwei')->where('post_id', $param['post_id'][$i])->where('gift_id', $gift_id_a)->order('id', 'desc')->limit('0,1')->value('post_xiaoshou');
									//$ticheng = '0';
								}else{
									$ticheng = '0';
								}
								$gift_id = Db::name('order')->where('id', $find['id'])->value('gift_id');
								//礼包销售提成
								$person_price1 = Db::name('gift_shop_price')->where('shop_id', $shop_id)->where('gift_id', $gift_id)->count();
								if($person_price1=='0'){
									$person_price ='0';  
								}else{
									$person_price = Db::name('gift_shop_price')->where('shop_id', $shop_id)->where('gift_id', $gift_id)->value('price');   
								}
								//计算总提成
								$assignor_price = $ticheng + $person_price;
								$param['assignor_price'][$i] = $assignor_price;
							}else{
								
							
							}
							/*******************************/
							
                            $is_agree = 1;
							
                            if ($param['single_id'][$i] == 9999) {
                                $is_agree = 2;
                            }
							//添加的信息
							/*echo "---------------------------------------------------------<br>";
							echo "ceshi1".$param['assignor_id'][$i]."<br>";
							echo "ceshi2".$param['assignor_price'][$i]."<br>";
							echo "ceshi3".$param['single_id'][$i]."<br>";
							echo "ceshi4".$find['id']."<br>";
							echo "ceshi5".$param['typea'][$i]."<br>";
							echo "ceshi6".$is_agree."<br>";
							echo "ceshi7".$find['order_type']."<br>";
							echo "ceshi8".$param['assignor_content'][$i]."<br>";
							echo "ceshi9".date('Y-m-d H:i:s', time())."<br>";
							echo "ceshi10".$shop_id."<br>";*/
							//echo "岗位".$param['typea'][$i]."信息".$param['post_id'][$i]."<br>";
							//echo "<a style='display:none'>".$param['post_id'][$i]."</a>";
							//echo "---------------------------------------------------------<br>";
							//echo "";
							//添加的信息结束
                            $shop_assignor_records_id = Db::name('shop_assignor_records')->insertGetId(

                                ['assignor_id' => $param['assignor_id'][$i],

                                    'assignor_price' => $param['assignor_price'][$i],
									'post_id' => $param['post_id'][$i],
									'pici'=> $param['pici'][$i],

                                    'single_id' => $param['single_id'][$i],

                                    'order_id' => $find['id'],
									'type' => $param['typea'][$i],
									'is_agree' => $is_agree,
                                    'order_type' => $find['order_type'],

                                    'assignor_content' => $param['assignor_content'][$i],

                                    'create_time' => date('Y-m-d H:i:s', time()),

                                    'shop_id' => $shop_id

                                ]);
							//新增日志
							//根据类型判断是服务提成还是销售提成
							if($param['typea'][$i]=='1'){
								$content_a =$content_a.'提成类型:服务提成'; 
							}elseif($param['typea'][$i]=='2'){
								$content_a =$content_a.'提成类型：售卖提成'; 
							}
							///服务门店
							$shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');
							$order_num_a = Db::name('order')->where('id',$find['id'])->value('order_number');
							$content_a = $content_a."--门店名称:".$shop_title;
							//查询提交的这个信息
							$content_a = $content_a."--提成金额：".$param['assignor_price'][$i];
							$content_a=$content_a."--服务人员：".Db::name('shop_assignor')->where('id',$param['assignor_id'][$i])->value('name');
							$content_a=$content_a."--消费日期：".date('Y-m-d H:i:s',time());
							$content_a=$content_a."--服务内容：".Db::name('single')->where('id',$param['assignor_content'][$i])->value('cat_name');
							$insert_log =  Db::name('member_log')->insert(
							 ['type_status' => 3,
							 'member_name' => \session('manage_user'),
							 'content' => $content_a,
							 'add_time' => time(),
							 'add_time_date'=> date('Y-m-d H:i:s',time()),
							 'type' => 1,
							 'member_id' => \session('manage_id'),
							 'member_jibie' => \session('manage_nick'),
							 'order_id' => $find['id'],
							 'order_num' => $order_num_a,
							 'order_type'=>$param['typea'][$i],
							]);
							$content_a = '';
							
							//新增日志
                            $new_array[] = $shop_assignor_records_id;
                        }
                        $order = DB::name('shop_assignor_records')->group('create_time')->where('id', 'in', $new_array)->order('id', 'desc')->select()->toArray(); //查询未同意的所有订单数据
						


                        foreach ($order as $k => &$v) {

                            $v['create_time_list'] = DB::name('shop_assignor_records')->group('assignor_content')->where('create_time', $v['create_time'])->select()->toArray();
							var_dump($v['create_time_list']);		
                        } //得到当前同一时间段 不用服务内容的唯一类;
//                        halt($order);
						session('ceshi_de','666'); 
                        foreach ($order as $v1) {
                            foreach ($v1['create_time_list'] as $v2) {
                                if ($v2['assignor_content'] != 9999) {
									$insert_log_libao =  Db::name('libao_log')->insert(
									 [
									 'member_name' => \session('manage_user'),
									 'content' => $content_a,
									 'add_time' => time(),
									 'add_time_date'=> date('Y-m-d H:i:s',time()),
									 'member_id' => \session('manage_id'),
									 'order_id' => $v2['order_id'],
									 'single_content' => $v2['assignor_content'],
									 'shifou_zengjia' => '0',
									]);	
									//防止重复扣次数
									//先查询这个订单这个分类的是零的有没有
									$shifou_kou_cishu = 
									DB::name('libao_log')
									->where('order_id', $v2['order_id'])
									->where('member_id', \session('manage_id'))
									->where('single_content', $v2['assignor_content'])
									->where('shifou_zengjia', 0)
									->count();
									
									if($shifou_kou_cishu > '0'){
										if(session('ceshi_de')=='666'){
											//扣次数日志
											$g_ret = Db::name('order_gift_count')
											    ->where('order_id', $v2['order_id'])
											    ->where('single_content', $v2['assignor_content'])
											    ->setDec('gift_count', 1);//订单礼包次数	
											//扣完次数，把所有的0都改成1
											$aaaa = Db::name('libao_log')
													->where('order_id', $v2['order_id'])
													->where('member_id', \session('manage_id'))
													->where('single_content', $v2['assignor_content'])
													->where('shifou_zengjia', 0)
													->update(['shifou_zengjia' => 1]);	
											}
											session('ceshi_de','777'); 
									var_dump(session('ceshi_de'));
									}
										
                                    if (!$g_ret) { //就是失败 $g_ret != true
                                        // abort(404);
                                        return json(['code' => 200, 'message' => $v1['id']]);
                                        //throw new \think\Exception($v2['id'], 500);
                                    }

                                }



                            }



                        }



                        $single_array = array_unique($single_array);//去重

                        $single_title = implode(',', $single_array);//打成字符串

                        Db::name('member_message')->insert(

                            ['member_id' => $find['member_id'],

                                'order_number' => $shop_assignor_records_id,

                                'type_id' => 4,

                                'title' => $find['gift_title'] . '礼包已设置,请确认使用',

                                'content' => '服务内容:' . $single_title,

                                'is_click' => 1,

                                'create_time' => date('Y-m-d H:i:s', time())

                            ]);

                        //Db::name('order_gift_count')->where('order_id',$id)->where('single_id',$single_id)->setDec('gift_count');//礼包剩余次数减少



                        //Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                        (new \app\index\controller\MemberMessage())->jpushMessage($find['member_id'], $find['gift_title'] . '礼包已设置,请确认使用', '服务内容:' . $single_title, 4);

                    }

                    Db::commit();

                } catch (Exception $e) {

                    Db::rollback();

                }



                wingo('1门店人员分配完毕.', Url::build('index'));

            }



            if (isset($param['status']) && ($param['status'] >= 10)) {

                //halt(input('post.status'));

                $fail_explain = Request::instance()->param('fail_explain','');

                if(strpos('5,7,8,9,10',(string)$level) === false){

                    fail('当前管理员无退款审核权限');

                }

                $refund_order_audit = Db::name('refund_order_audit')->where([

                    'order_id' => $find['id'],

                    'manage_id' => \session('manage_id'),

                ])->find();//当前管理员自己提交的数据

                if(!empty($refund_order_audit)) fail('已经申请过审核');

                if($level == 5){ //门店点击提交 店长-副经理-经理-财务-总经理

                    if(empty($refund_order_audit)){

                        (new RefundOrderAudit())->save([

                            'order_id' => $find['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => input('post.status'),

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => \session('shop_id'),

                            'shop_title' => Db::name('shop')->where('id',\session('shop_id'))->value('shop_title'),

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        Db::name('order')->where('id',$find['id'])->setField('is_read_5',1);

                        if($param['status'] == 12){
                            //Db::name('order')->where('id',$find['id'])->setField('status',12);
							Db::name('order')->where('id',$find['id'])->setField('status',5);	
							Db::name('order')->where('id',$find['id'])->setField('tui_status',2);	
                        }

                        wingo('门店申请退款审核',Url::build('index'));

                    }else{

                        fail('已经申请审核');

                    }

                }

                $refund_order_audit_5 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>5])->find();//门店是否提交审核数据

                $refund_order_audit_7 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>7])->find();//门店是否提交审核数据

                $refund_order_audit_8 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>8])->find();//门店是否提交审核数据

                $refund_order_audit_9 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>9])->find();//门店是否提交审核数据

                if($level == 7){ //副经理

                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $find['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => input('post.status'),

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$find['id'])->setField('is_read_7',1);

                    if($param['status'] == 12){

                        //Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);	
                    }

                    if($ret){

                        wingo('副经理申请退款审核',Url::build('index'));

                    }



                }

                if($level == 8){ //经理



                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $find['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => input('post.status'),

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$find['id'])->setField('is_read_8',1);

                    if($param['status'] == 12){

                       // Db::name('order')->where('id',$find['id'])->setField('status',12);
					   Db::name('order')->where('id',$find['id'])->setField('status',5);
					   Db::name('order')->where('id',$find['id'])->setField('tui_status',2);

                    }

                    if($ret){

                        wingo('经理申请退款审核',Url::build('index'));

                    }

                }

                if($level == 9){ //财务



                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $find['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => input('post.status'),

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$find['id'])->setField('is_read_9',1);

                    if($param['status'] == 12){

                        //Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);
                    }

                    if($ret){

                        wingo('财务申请退款审核',Url::build('index'));

                    }

                }

                if($level == 10){ //总经理



                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    if(empty($refund_order_audit_9)) fail('财务没有通过退款审核');

                    Db::name('order')->where('id',$find['id'])->setField('is_read_10',1);

                    if($param['status'] == 12){

                        //Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);
                    }

                    if($param['status'] == 11){

                        $find = Db::name('order')->find($id);

                        if ($find['pay_type'] == '2') {

                            $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '', $find['shop_order_number']);



                            if ($ret->code !== '10000') {

                                fail($ret->sub_msg);

                            }

                            //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

                        } else if ($find['pay_type'] == '1') {

                            //halt('wx');

                            $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

                            //halt($ret);

                            if ($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

                        }

                        $ret = Db::name('order')->where('id', $param['id'])->update(['status' => input('post.status')]);

                        if ($ret !== false) {

                            (new Order())->refund($find['member_id'], $find['order_number']);

                            $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);

//                            if ($refund_ret !== false) {

//                                win('退货款处理完毕', Url::build('index'));

//                            }

                        }

                        $ret = (new RefundOrderAudit())->save([

                            'order_id' => $find['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => input('post.status'),

                            'is_read' => 1,

                            'level' => $level,



                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        Db::name('member_card')->where('order_id',$find['id'])->delete();

                        if($ret){

                            Db::name('member_distribution_records')->where(['order_number' => $find['order_number']])->delete();

                            wingo('总经理同意退款中',Url::build('index'));

                        }

                    }



                }

//                if($level == 1){

//                    $ret = (new RefundOrderAudit())->save([

//                        'order_id' => $find['id'],

//                        'manage_id' => \session('manage_id'),

//                        'status' => input('post.status'),

//                        'is_read' => 1,

//                        'level' => $level,

//

//                        'fail_explain' => $fail_explain,

//                        'create_time' => date('Y-m-d H:i:s',time())

//                    ]);

//                    Db::name('member_card')->where('order_id',$find['id'])->delete();

//                    if($ret){

//                        Db::name('member_distribution_records')->where(['order_number' => $find['order_number']])->delete();

//                        wingo('管理员退款中',Url::build('index'));

//                    }

//                }











            } //退款逻辑end

//            if (isset($param['status']) && ($param['status'] == 11 || $param['status'] == 12)) {

//

//                if ($find['pay_type'] == '2') {

//                    $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '',$find['shop_order_number']);

//

//                    if($ret->code !== '10000'){

//                        fail($ret->sub_msg);

//                    }

//                    //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

//                } else if ($find['pay_type'] == '1') {

//                    //halt('wx');

//

//                    $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

//                    if($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

//

//                }

//                $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

//                if ($ret !== false) {

//                    $refund_ret = Db::name('order_refund')->where('order_id',$id)->update(['fail_explain' =>$param['fail_explain']]);

//                    if($refund_ret !== false){

//                        win('退款处理完毕', Url::build('index'));

//                    }

//                }

//            }

//            if (isset($param['status']) && ($param['status'] == 11)) {

//                $find = Db::name('order')->find($id);

//                if ($find['pay_type'] == '2') {

//                    $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '',$find['shop_order_number']);

//                    if($ret->code !== '10000'){

//                        fail($ret->sub_msg);

//                    }

//                    //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

//                } else if ($find['pay_type'] == '1') {

//                    //halt('wx');

//                    $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

//                    if($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

//                }

//                $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

//                if ($ret !== false) {

//                    (new Order())->refund($find['member_id'],$find['order_number']);

//                    $refund_ret = Db::name('order_refund')->where('order_id',$id)->update(['fail_explain' =>$param['fail_explain']]);

//                    if($refund_ret !== false){

//                        win('退货款处理完毕', Url::build('index'));

//                    }

//                }

//            }

//

//            if (isset($param['status']) && ($param['status'] == 12)) {//退款中变成 进行中

//              $ret = Db::name('order')->where('id', $param['id'])->update(['status' => 6]);

//                if ($ret !== false) {

//                    $refund_ret = Db::name('order_refund')->where('order_id',$id)->update(['fail_explain' =>$param['fail_explain']]);

//                    if($refund_ret !== false){

//                        win('退货款失败处理完毕', Url::build('index'));

//                    }

//                }

//            }

        }



        $info = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

            ->field('o.*,m.username,m.car_number m_car_numb,m.car_model,m.is_certification,m.brand_number,m.id_code,s.shop_title')

            ->where('o.id', $param['id'])

            ->find();

        if($info['status'] == 10 || $info['status'] == 11 || $info['status'] == 12){

            $info['refund_create_time'] = Db::name('order_refund')->where('order_id',$info['id'])->value('create_time');

        }

        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();
		$post_list = Db::name('job jb')->join('shop s','jb.shop_id = s.id','left')->field('jb.*,s.shop_title')->where('jb.status',1)->select();


        $gift_records = Db::name('gift_assignor_records gr')->join('shop s','gr.shop_id = s.id','left')->field('gr.*,s.shop_title')->where('order_id',$id)->select();

        //$shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;



        if(\session('auding_status') == 1){



            $shop_id = \session('shop_id');



        }else{



            $shop_id = $shop_list[0]['id'];

        }

//        20200611

//        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->where('is_delete',1)->select();

        $shop_assignor = Db::name('shop_assignor')->where('is_delete',1)->select();



        if(\session('role_id') == 1){

            $is_show = [];





        }else{

            if(isset($param['table'])){

                $is_show['sar.is_show'] = ['eq',1];

                

            }else{

                $is_show = [];

            }



        }

        $where_sar = [];

        if(isset($param['table'])) $where_sar['sar.is_agree'] = ['eq',2];

        $shop_assignor_records = Db::name('shop_assignor_records sar')

            ->join('shop','shop.id = sar.shop_id','left')

            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id','left')
			->join('job jb','jb.id = sar.post_id','left')

            ->where('order_id', $info['id'])

            ->where($is_show)



            ->where($where_sar)

            ->order('sar.id','desc')

            ->field('sar.*,shop.shop_title,sa.name,s.cat_name,jb.title')

            ->select()->toArray();
			
		$shop_assignor_records1 = Db::name('shop_assignor_records sar')

            ->join('shop','shop.id = sar.shop_id','left')

            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id','left')
			->join('job jb','jb.id = sar.post_id','left')

            ->where('order_id', $info['id'])

            ->where($is_show)

			->where('assignor_id','neq','')

            ->where($where_sar)

            ->order('sar.id','desc')

            ->field('sar.*,shop.shop_title,sa.name,s.cat_name,jb.title')

            ->select()->toArray();


        if(!empty($shop_assignor_records)){

            foreach ($shop_assignor_records as $k => &$v){

                $v['assignor_content'] = Db::name('single')->where('id',$v['assignor_content'])->value('cat_name');

            }

        }

        $service_order_goods = Db::name('service_order_goods soo')

            ->join('shop','shop.id = soo.shop_id','left')

            ->join('shop_spec_attr ssa','ssa.id = soo.spec_id','left')

            ->join('shop_goods sg','sg.id = ssa.goods_id','left')

            ->where('order_id', $info['id'])

            ->field('soo.*,shop.shop_title,ssa.attribute,sg.title')

            ->select();





        $refund_order_audit_records = (new RefundOrderAudit())

            ->alias('roa')

            ->join('manager m','roa.manage_id = m.id')

            ->field('roa.*,m.username')

            ->where('order_id',$find['id'])

            ->select();

        //审核会员数量 不管通过不通过;

        $count = (new RefundOrderAudit())->where('order_id',$find['id'])->where('status','11')->count();

        $refund_button = false; //这么判断 其他人员肯定是false 就没有退款按钮

//        if($level == 5){

//            if($count == 0){

//                $refund_button = true;

//            }

//        }



        if($level == 7){

            if($count == 0){

                $refund_button = true;

            }

        }

        if($level == 8){



            if($count == 1){

                $refund_button = true;

            }

        }

        if($level == 9){





            if($count == 2){

                $refund_button = true;

            }

        }

        if($level == 10){

            if($count == 3){

                $refund_button = true;

            }

        }

        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }



        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id','left')

            ->join('shop s','s.id = ssa.shop_id')

            ->where($where)

            ->where('ssa.shop_id','gt',0)

            ->where('s.auding_status',2)

            ->where('s.is_delete',1)

            ->field('sg.title,ssa.*,s.shop_title')

            ->paginate(1000, false, ['query' => $param])->each(function ($item, $key)  use ($where){



            });

        //原订单礼包订单商品 //记录



        if($info['t_type'] == 1){ //礼包

            $order_gift_count = Db::name('order_gift_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->select()->toArray();

            

            if(!empty($order_gift_count)){

                foreach ($order_gift_count as $k => &$v){

                    $v['cat_name2'] = Db::name('single')->where('id',$v['single_content'])->value('cat_name');

                }

            }

            $now_gift_count = Db::name('order_gift_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.gift_count','gt',0)

                ->whereTime('end_time','>=',time())

                ->group('ogc.single_id')

                ->select()->toArray();//剩余次数大于0的礼包记录数 默认礼包分类



            if(empty($now_gift_count)){

                $now_gift_count[0]['single_id'] = '';

            }

            $single_id_array = Db::name('order_gift_count')

                ->alias('ogc')

                ->join('single s','ogc.single_content = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.single_id',$now_gift_count[0]['single_id'])

                ->where('ogc.gift_count','gt',0)

                ->whereTime('end_time','>=',time())

                ->column('ogc.single_content');//剩余次数大于0的礼包记录数 默认礼包分类

        }else{ //会员卡

            $order_gift_count = Db::name('order_mc_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->select()->toArray();

            if(!empty($order_gift_count)){

                foreach ($order_gift_count as $k => &$v){

                    $v['cat_name2'] = Db::name('single')->where('id',$v['single_content'])->value('cat_name');

                }

            }



            $now_gift_count = Db::name('order_mc_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.gift_count','gt',0)

                ->group('ogc.single_id')

                ->select()->toArray();//剩余次数大于0的礼包记录数 默认礼包分类



            if(empty($now_gift_count)){

                $now_gift_count[0]['single_id'] = '';

            }



            $single_id_array = Db::name('order_mc_count')

                ->alias('ogc')

                ->join('single s','ogc.single_content = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.single_id',$now_gift_count[0]['single_id'])

               // ->whereTime('end_time','>=',time())

                ->where('ogc.gift_count','gt',0)

                ->column('ogc.single_content');//剩余次数大于0的礼包记录数 默认礼包分类

        }





        if(!empty($now_gift_count)){

            foreach ($now_gift_count as $k => &$v){ //默认第一个门店的服务类人员金额

                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['single_id'])->value('person_price');

                if(is_null($person_price)) $person_price = '0.00';

               $v['person_price'] =  $person_price; //好像没啥用

                //$single_id_array[] = $v['single_content'];



            }

        }



        if(session('role_id') != 1){

            $info['username'] = hideStr($info['username'],1,6);

        }



        if(!empty($now_gift_count)){

            $service_people_price2 = Db::name('shop_service_price')

                ->alias('ssp')

                ->join('single s','ssp.single_id = s.id','right')

                ->where('shop_id',$shop_id)

                ->where('s.id','in',$single_id_array)

                ->where('auding_status',2)

//                ->where('is_delete',1)

                ->field('s.id,s.cat_name,ssp.person_price')

                ->select(); //服务人员提成;



            //dump($service_people_price2);

            $service_people_price3 = Db::name('shop_service_price')

                ->alias('ssp')

                ->join('single s','ssp.single_id = s.id','right')

                ->where('shop_id',$shop_id)

                ->where('s.parent_id','eq',$now_gift_count[0]['single_id'])

                ->where('auding_status',2)

                ->where('is_delete',1)

                ->field('s.id,s.cat_name,ssp.person_price')

                ->select(); //服务人员提成;

        }else{

            halt('else');

            $service_people_price2 = $service_people_price3 = '';

        }

        if($info['t_type'] == 1){

            if($service_people_price2->isEmpty()){

/*               echo '<script src="/static/console/js/jquery.min.js"></script>

//<script src="/static/console/js/select/select2.full.min.js">alert("1324")</script>';



               echo "<script>alert('请联系总后台设置人员提成或数据已')</script>";*/

            }

        }



        $template = '';

        if(isset($param['table'])) $template = 'service_order_table';

        $info['cat_name'] = $info['gift_title'];

        $info['one_cat'] = '';





        $info['mc_single_pic'] = Db::name('system_card')->where('id',$info['system_card_id'])->value('single_pic');

        $gift_shop_price = Db::name('gift_shop_price')->where('gift_id',$info['gift_id'])->where('shop_id',$shop_id)->value('price');

        $service_people_price2 = $service_people_price2->toArray();

        foreach ($service_people_price2 as $k49 => &$v49){

            //$v49['person_price'] = $gift_shop_price+$v49['person_price'];

        }



        $gift_shop_backstage = Db::name('gift_shop_price')->where('gift_id',$info['gift_id'])->where('shop_id',$shop_id)->value('price');

        if(is_null($gift_shop_backstage)) $gift_shop_backstage = 0;//默认线下门店礼包服务人员提成





        $mwhere['status'] = ['eq',1];

        $mwhere['start_time'] = ['elt',time()];

        $mwhere['end_time'] = ['gt',time()];

        $mwhere = "(type = 4 or type = 3) and status = 1";

        $result = (new  \app\index\model\MemberCoupon)->where($mwhere)

            ->field('id,type,single_id,title,minus_price,total_price,content,status,start_time,end_time')

            ->where('total_price','elt',$info['order_price'])

            ->order(['id' => 'desc'])

            ->fetchSql(false)

            //->whereOr('type',3)

            ->where('member_id',$info['member_id'])

            ->select();

        $member_car_list1 = Db::name('member')->where('id',$info['member_id'])->column('car_number');

        $member_car_list2 = Db::name('member_car_list')->where('member_id',$info['member_id'])->group('car_number')->column('car_number');

        $member_car_list3 = Db::name('order')->where('member_id',$info['member_id'])->group('car_number')->column('car_number');

        $member_car_list4 = array_merge($member_car_list1,$member_car_list2,$member_car_list3);

        $member_car_list4 = array_unique($member_car_list4);

        if(!empty($member_car_list4)){

            foreach ($member_car_list4 as $k =>&$v){

                if(empty($v)){

                    unset($member_car_list4[$k]);

                }

            }

        }



        $user_coupon = http_gets("http://lihai.xmdonkey.com/index.php/index/member_coupon/index/member_id/{$info['member_id']}/status/1/order_price/{$info['order_price']}/type/4/single_id/{$info['gift_id']}");

        $coupon_array = json_decode($user_coupon,true)['data']['data'];

        $gift_card = Db::name('gift_card')->where('order_id',$id)->find();



        $this->assign('gift_card',$gift_card);



        if(!empty($param['gid'])){

            $gift_order_two = Db::name('gift_order_two')->where('id',$param['gid'])->value('order_number_two');



            $this->assign('gift_order_twoabc',$gift_order_two);

        }
		//////////////////////////////////////批次///////////////////////////////////////////////////////////
		$pici_status = Db::name('shop_assignor_records')->where('order_id',$id)->count();
		if($pici_status =='0'){
			$pici = '1';
			$picia = '1';
		}else{
			//查询之后一个批次的数
			$pici = Db::name('shop_assignor_records')->where('order_id',$id)->order('pici','desc')->value('pici') + 1;
			$picia = Db::name('shop_assignor_records')->where('order_id',$id)->order('pici','desc')->value('pici');
		}
		$is_agree = '0';
		if(\session('role_id')=='5'){
			$pici_list = Db::name('shop_assignor_records')->where('order_id',$id)->where('pici_status','1')->Distinct(true)->field('pici,is_agree_agree')->select()->toArray();
			foreach($pici_list as &$v){
				$v['shifou_tongyi'] = Db::name('shop_assignor_records')->where('order_id',$id)->where('pici',$v['pici'])->where('is_agree','1')->count();
				if($v['shifou_tongyi'] > '0'){
					$v['is_agree_agree'] = '0';
				}else{
					$v['is_agree_agree']='1';
				}
				
				//var_dump($v['pici']."--".$v['shifou_tongyi']."--".$v['is_agree_agree']);
			}
			
		}else{
			$pici_list = Db::name('shop_assignor_records')->where('order_id',$id)->Distinct(true)->field('pici')->select()->toArray();
			foreach($pici_list as &$v){
				$v['is_agree_agree']='1';
			}
		
		}
		//halt($pici_list);
		//var_dump($pici_list);
		
		//$pici_list = Db::name('shop_assignor_records')->where('order_id',$id)->Distinct(true)->field('pici')->select();
		
		//////////////////////////////////////批次///////////////////////////////////////////////////////////


//        dump(json_decode($user_coupon,true));
		//var_dump($pici_list);
        return view($template, [

            'member_car_list4' => $member_car_list4,
			'is_agree_agree'=>$is_agree,
            'member_coupon' => $coupon_array,
			'pici_list'=>$pici_list,
            'gift_shop_backstage' => $gift_shop_backstage,

            'shop_list' => $shop_list,
			'pici'=>$pici,
			'picia'=>$picia,
			
			
			'post_list' => $post_list,

            'item' => $info,

            'order_gift_count' => $order_gift_count,

            'now_gift_count' => json_encode($now_gift_count),
			'shop_assignor_records1' => $shop_assignor_records1,
            'service_people_price2' => json_encode($service_people_price2),

            'service_people_price3' => json_encode($service_people_price3),

            'refund' => $refund,

            'shop_assignor' => $shop_assignor,

            'gift_assignor_records' => $shop_assignor_records,

            'shop_assignor_records' => $shop_assignor_records,

            'service_order_goods' => $service_order_goods,

            'refund_order_audit_records' => $refund_order_audit_records,

            'refund_button' => $refund_button,

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

        ]);

    }





    /**

     * @param $id

     * @return array|mixed|\think\response\View

     * 打印

     */

    public function update_dayin($id)

    {

        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10

        $param = Request::instance()->param();

        $find = Db::name('order')->find($id);

        $auding_status = Session::get('auding_status');

        if($auding_status == 2){

            Db::name('order o')->where('id',$id)->setField('is_read',1);

        }else{

            Db::name('order o')->where('id',$id)->setField('is_read_shop',1);

        }

        //礼包消息读取

        $gift_news = Db::name('gift_news')->where('order_id', $id)->where('manage_id',session('manage_id'))->find();

        if(empty($gift_news)){ //如果没有就添加 如果有不处理

            Db::name('gift_news')->insert(['order_id' => $id,'manage_id' => session('manage_id')]);

        }

        $refund = Db::name('order_refund ors')->field('ors.*,rr.title')->where('order_id',$find['id'])->join('refund_reason rr','ors.reason_id = rr.id')->find();

        if (Request::instance()->isPost()) {

            $status = Db::name('order')->where('id',$id)->value('status');

            $gift_end_time = Db::name('order')->where('id',$id)->value('gift_end_time');

            if(($gift_end_time) < date('Y-m-d H:i:s',time())){

                //fail('礼包已经过期,不能再添加服务');

            }

            if ($status == 6) {

                $shop_assignor_records = [];

                if(empty($param['assignor_id'])){

                    //fail('请添加门店人员');

                }

                if(empty($param['shop_id'])){

                    //  fail('门店人员必须添加');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }

                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        $auding_status = Session::get('auding_status');

                        if($auding_status == 1){

                            $shop_id =  \session('shop_id');

                        }else{

                            $shop_id = Request::instance()->param()['shop_id'][$i];

                        }



                        (new ServiceOrderGoods())->save([

                            'shop_id' => $shop_id,

                            'order_id' => $find['id'],

                            'cat_id' => $param['cat_id'][$i],

                            'spec_id' => $param['spec_id'][$i],

                            'number' => $param['number'][$i],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                    }

                    //(new ServiceOrderGoods())->saveAll($service_order_goods);

                }

                if(!empty($param['assignor_id'])){

                    //$single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

                    $single_title = Db::name('single')->where('id',$param['single_id'][0])->value('cat_name');

                    //$assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {

                        $auding_status = Session::get('auding_status');

                        if($auding_status == 1){

                            $shop_id =  \session('shop_id');

                        }else{

                            $shop_id = Request::instance()->param()['shop_id'][$i];

                        }

//                        $shop_assignor_records[$i]['order_id'] = $find['id'];

//                        $shop_assignor_records[$i]['shop_id'] = $shop_id;

//                        $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

//                        $shop_assignor_records[$i]['single_id'] = $single_id;

//                        $shop_assignor_records[$i]['assignor_price'] = $assignor_price;

//                        $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

//                        $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

//                        $shop_assignor_records[$i]['order_type'] = $find['order_type'];



                        $shop_assignor_records_id = Db::name('shop_assignor_records')->insertGetId(

                            ['assignor_id' => $param['assignor_id'][$i],

                                'assignor_price' => $param['assignor_price'][$i],
								'type' => $param['typea'][$i],
                                'single_id' => $param['single_id'][$i],

                                'order_id' => $find['id'],

                                'order_type' => $find['order_type'],

                                'assignor_content' => $param['assignor_content'][$i],

                                'create_time' => date('Y-m-d H:i:s',time()),

                                'shop_id' => $shop_id

                            ]);



                        Db::name('member_message')->insert(

                            ['member_id' => $find['member_id'],

                                'order_number' => $shop_assignor_records_id,

                                'type_id' => 4,

                                'title' => $find['gift_title'].'礼包已设置,请确认使用',

                                'content' => '服务类型:'.$single_title,

                                'is_click' => 1,

                                'create_time' => date('Y-m-d H:i:s', time())

                            ]);



                    }

                    //Db::name('order_gift_count')->where('order_id',$id)->where('single_id',$single_id)->setDec('gift_count');//礼包剩余次数减少

                    (new \app\index\controller\MemberMessage())->jpushMessage($find['member_id'], $find['gift_title'].'礼包已设置,请确认使用','服务类型:'.$single_title, 4);



                    //Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                }

                if(empty($param['assignor_id'])){ //如果没有添加人员就是 普通的修改数据

                    //fail('请添加门店人员');

                    halt($param);

                }else{

                    Db::name('order')->where('id',$id)->where('status',6)->update(['status' => 5]);

                    win('门店3人员分配完毕', Url::build('index'));

                }





            }

            if ($status == 5 || $status == 4) {

                $shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;

                //if(empty($shop_id)) fail('当前管理员不是门店管理员');

                if(empty($param['assignor_id'])){

                    fail('请添加门店人员');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }

                if(isset($param['shop_id']) &&  count(array_unique($param['shop_id'])) >= 2){

                    //fail('一次只能服务一个门店');

                }

                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                    $service_order_goods = [];

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        $auding_status = Session::get('auding_status');

                        if($auding_status == 1){

                            $shop_id =  \session('shop_id');

                        }else{

                            $shop_id = Request::instance()->param()['shop_id'][$i];

                        }

                        //服务商品

                        (new ServiceOrderGoods())->save([

                            'shop_id' => $shop_id,

                            'order_id' => $find['id'],

                            'cat_id' => $param['cat_id'][$i],

                            'spec_id' => $param['spec_id'][$i],

                            'number' => $param['number'][$i],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                    }

                    //(new ServiceOrderGoods())->saveAll($service_order_goods);

                }

                if(!empty($param['assignor_id'])){

                    //$single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了



                    //$assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                    $single_title = '';

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {



                        $single_array[] = Db::name('single')->where('id',$param['assignor_content'][$i])->value('cat_name');

                        $auding_status = Session::get('auding_status');

                        if($auding_status == 1){

                            $shop_id =  \session('shop_id');

                        }else{

                            $shop_id = Request::instance()->param()['shop_id'][$i];

                        }

//                        $shop_assignor_records[$i]['order_id'] = $find['id'];

//                        $shop_assignor_records[$i]['shop_id'] = $shop_id;

//                        $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

//                        $shop_assignor_records[$i]['single_id'] = $single_id;

//                        $shop_assignor_records[$i]['assignor_price'] = $assignor_price;

//                        $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

//                        $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

//                        $shop_assignor_records[$i]['order_type'] = $find['order_type'];



                        $shop_assignor_records_id = Db::name('shop_assignor_records')->insertGetId(

                            ['assignor_id' => $param['assignor_id'][$i],

                                'assignor_price' => $param['assignor_price'][$i],

                                'single_id' => $param['single_id'][$i],
								'type' => $param['typea'][$i],
                                'order_id' => $find['id'],

                                'order_type' => $find['order_type'],

                                'assignor_content' => $param['assignor_content'][$i],

                                'create_time' => date('Y-m-d H:i:s',time()),

                                'shop_id' => $shop_id

                            ]);







                    }

                    $single_array = array_unique($single_array);//去重

                    $single_title = implode(',',$single_array);//打成字符串

                    Db::name('member_message')->insert(

                        ['member_id' => $find['member_id'],

                            'order_number' => $shop_assignor_records_id,

                            'type_id' => 4,

                            'title' => $find['gift_title'].'礼包已设置,请确认使用',

                            'content' => '服务内容:'.$single_title,

                            'is_click' => 1,

                            'create_time' => date('Y-m-d H:i:s', time())

                        ]);

                    //Db::name('order_gift_count')->where('order_id',$id)->where('single_id',$single_id)->setDec('gift_count');//礼包剩余次数减少



                    //Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                    (new \app\index\controller\MemberMessage())->jpushMessage($find['member_id'], $find['gift_title'].'礼包已设置,请确认使用','服务内容:'.$single_title, 4);

                }



                win('门店4人员分配完毕.', Url::build('index'));

            }



            if (isset($param['status']) && ($param['status'] >= 10)) {



                $fail_explain = Request::instance()->param('fail_explain','');

                if(strpos('5,7,8,9,10',(string)$level) === false){

                    fail('当前管理员无退款审核权限');

                }

                $refund_order_audit = Db::name('refund_order_audit')->where([

                    'order_id' => $find['id'],

                    'manage_id' => \session('manage_id'),

                ])->find();//当前管理员自己提交的数据

                if(!empty($refund_order_audit)) fail('已经申请过审核');

                if($level == 5){ //门店点击提交 店长-副经理-经理-财务-总经理

                    if(empty($refund_order_audit)){

                        (new RefundOrderAudit())->save([

                            'order_id' => $find['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => $param['status'],

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => \session('shop_id'),

                            'shop_title' => Db::name('shop')->where('id',\session('shop_id'))->value('shop_title'),

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        Db::name('order')->where('id',$find['id'])->setField('is_read_5',1);

                        if($param['status'] == 12){

                            //Db::name('order')->where('id',$find['id'])->setField('status',12);
							Db::name('order')->where('id',$find['id'])->setField('status',5);
							Db::name('order')->where('id',$find['id'])->setField('tui_status',2);	
                        }

                        win('门店申请退款审核',Url::build('index'));

                    }else{

                        fail('已经申请审核');

                    }

                }

                $refund_order_audit_5 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>5])->find();//门店是否提交审核数据

                $refund_order_audit_7 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>7])->find();//门店是否提交审核数据

                $refund_order_audit_8 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>8])->find();//门店是否提交审核数据

                $refund_order_audit_9 = Db::name('refund_order_audit')->where(['order_id' => $find['id'],'status' => 11, 'level' =>9])->find();//门店是否提交审核数据

                if($level == 7){ //副经理

                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $find['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => $param['status'],

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$find['id'])->setField('is_read_7',1);

                    if($param['status'] == 12){

                        //Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);
                    }

                    if($ret){

                        win('副经理申请退款审核',Url::build('index'));

                    }



                }

                if($level == 8){ //经理



                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $find['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => $param['status'],

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$find['id'])->setField('is_read_8',1);

                    if($param['status'] == 12){

                        //Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);
                    }

                    if($ret){

                        win('经理申请退款审核',Url::build('index'));

                    }

                }

                if($level == 9){ //财务



                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $find['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => $param['status'],

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$find['id'])->setField('is_read_9',1);

                    if($param['status'] == 12){

                        //Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);
                    }

                    if($ret){

                        win('财务申请退款审核',Url::build('index'));

                    }

                }

                if($level == 10){ //总经理



                    //if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    if(empty($refund_order_audit_9)) fail('财务没有通过退款审核');

                    Db::name('order')->where('id',$find['id'])->setField('is_read_10',1);

                    if($param['status'] == 12){

                       // Db::name('order')->where('id',$find['id'])->setField('status',12);
						Db::name('order')->where('id',$find['id'])->setField('status',5);
						Db::name('order')->where('id',$find['id'])->setField('tui_status',2);
                    }

                    if($param['status'] == 11){

                        $find = Db::name('order')->find($id);

                        if ($find['pay_type'] == '2') {

                            $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '', $find['shop_order_number']);

                            if ($ret->code !== '10000') {

                                fail($ret->sub_msg);

                            }

                            //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

                        } else if ($find['pay_type'] == '1') {

                            //halt('wx');

                            $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

                            if ($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

                        }

                        $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

                        if ($ret !== false) {

                            (new Order())->refund($find['member_id'], $find['order_number']);

                            $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);

                            if ($refund_ret !== false) {

                                win('退货款处理完毕', Url::build('index'));

                            }

                        }

                        $ret = (new RefundOrderAudit())->save([

                            'order_id' => $find['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => $param['status'],

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => 0,

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        Db::name('member_card')->where('order_id',$find['id'])->delete();

                        if($ret){

                            win('总经理同意退款中',Url::build('index'));

                        }

                    }



                }











            } //退款逻辑end

//            if (isset($param['status']) && ($param['status'] == 11 || $param['status'] == 12)) {

//

//                if ($find['pay_type'] == '2') {

//                    $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '',$find['shop_order_number']);

//

//                    if($ret->code !== '10000'){

//                        fail($ret->sub_msg);

//                    }

//                    //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

//                } else if ($find['pay_type'] == '1') {

//                    //halt('wx');

//

//                    $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

//                    if($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

//

//                }

//                $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

//                if ($ret !== false) {

//                    $refund_ret = Db::name('order_refund')->where('order_id',$id)->update(['fail_explain' =>$param['fail_explain']]);

//                    if($refund_ret !== false){

//                        win('退款处理完毕', Url::build('index'));

//                    }

//                }

//            }

//            if (isset($param['status']) && ($param['status'] == 11)) {

//                $find = Db::name('order')->find($id);

//                if ($find['pay_type'] == '2') {

//                    $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '',$find['shop_order_number']);

//                    if($ret->code !== '10000'){

//                        fail($ret->sub_msg);

//                    }

//                    //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

//                } else if ($find['pay_type'] == '1') {

//                    //halt('wx');

//                    $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

//                    if($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

//                }

//                $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

//                if ($ret !== false) {

//                    (new Order())->refund($find['member_id'],$find['order_number']);

//                    $refund_ret = Db::name('order_refund')->where('order_id',$id)->update(['fail_explain' =>$param['fail_explain']]);

//                    if($refund_ret !== false){

//                        win('退货款处理完毕', Url::build('index'));

//                    }

//                }

//            }

//

//            if (isset($param['status']) && ($param['status'] == 12)) {//退款中变成 进行中

//              $ret = Db::name('order')->where('id', $param['id'])->update(['status' => 6]);

//                if ($ret !== false) {

//                    $refund_ret = Db::name('order_refund')->where('order_id',$id)->update(['fail_explain' =>$param['fail_explain']]);

//                    if($refund_ret !== false){

//                        win('退货款失败处理完毕', Url::build('index'));

//                    }

//                }

//            }

        }



        $info = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

            ->field('o.*,m.username,m.car_number,m.is_certification,m.brand_number,m.id_code,s.shop_title')

            ->where('o.id', $param['id'])

            ->find();

        if($info['status'] == 10 || $info['status'] == 11 || $info['status'] == 12){

            $info['refund_create_time'] = Db::name('order_refund')->where('order_id',$info['id'])->value('create_time');

        }

        $shop_list = Db::name('shop')->where('is_delete',1)->where('auding_status',2)->select();

        $gift_records = Db::name('gift_assignor_records gr')->join('shop s','gr.shop_id = s.id','left')->field('gr.*,s.shop_title')->where('order_id',$id)->select();

        //$shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;

        if(\session('auding_status') == 1){

            $shop_id = \session('shop_id');

        }else{

            $shop_id = $shop_list[0]['id'];

        }

        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->where('is_delete',1)->select();





        $shop_assignor_records = Db::name('shop_assignor_records sar')

            ->join('shop','shop.id = sar.shop_id','left')

            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id')

            ->where('order_id', $info['id'])

            ->order('sar.id','desc')

            ->field('sar.*,shop.shop_title,sa.name,s.cat_name')

            ->select()->toArray();

        if(!empty($shop_assignor_records)){

            foreach ($shop_assignor_records as $k => &$v){

                $v['assignor_content'] = Db::name('single')->where('id',$v['assignor_content'])->value('cat_name');

            }

        }

        $service_order_goods = Db::name('service_order_goods soo')

            ->join('shop','shop.id = soo.shop_id','left')

            ->join('shop_spec_attr ssa','ssa.id = soo.spec_id','left')

            ->join('shop_goods sg','sg.id = ssa.goods_id','left')

            ->where('order_id', $info['id'])

            ->field('soo.*,shop.shop_title,ssa.attribute,sg.title')

            ->select();





        $refund_order_audit_records = (new RefundOrderAudit())

            ->alias('roa')

            ->join('manager m','roa.manage_id = m.id')

            ->field('roa.*,m.username')

            ->where('order_id',$find['id'])

            ->select();

        //审核会员数量 不管通过不通过;

        $count = (new RefundOrderAudit())->where('order_id',$find['id'])->where('status','11')->count();

        $refund_button = false; //这么判断 其他人员肯定是false 就没有退款按钮

//        if($level == 5){

//            if($count == 0){

//                $refund_button = true;

//            }

//        }

        if($level == 7){

            if($count == 0){

                $refund_button = true;

            }

        }

        if($level == 8){

            if($count == 1){

                $refund_button = true;

            }

        }

        if($level == 9){

            if($count == 2){

                $refund_button = true;

            }

        }

        if($level == 10){

            if($count == 3){

                $refund_button = true;

            }

        }

        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }



        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id','left')

            ->join('shop s','s.id = ssa.shop_id')

            ->where($where)

            ->where('ssa.shop_id','gt',0)

            ->where('s.auding_status',2)

            ->where('s.is_delete',1)

            ->field('sg.title,ssa.*,s.shop_title')

            ->paginate(1000, false, ['query' => $param])->each(function ($item, $key)  use ($where){



            });

        //原订单礼包订单商品 //记录



        if($info['t_type'] == 1){ //礼包

            $order_gift_count = Db::name('order_gift_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->select()->toArray();

            if(!empty($order_gift_count)){

                foreach ($order_gift_count as $k => &$v){

                    $v['cat_name2'] = Db::name('single')->where('id',$v['single_content'])->value('cat_name');

                }

            }

            $now_gift_count = Db::name('order_gift_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.gift_count','gt',0)

                ->whereTime('end_time','>=',time())

                ->group('ogc.single_id')

                ->select()->toArray();//剩余次数大于0的礼包记录数 默认礼包分类

            if(empty($now_gift_count)){

                $now_gift_count[0]['single_id'] = '';

            }

            $single_id_array = Db::name('order_gift_count')

                ->alias('ogc')

                ->join('single s','ogc.single_content = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.single_id',$now_gift_count[0]['single_id'])

                ->where('ogc.gift_count','gt',0)

                ->whereTime('end_time','>=',time())

                ->column('ogc.single_content');//剩余次数大于0的礼包记录数 默认礼包分类

        }else{ //会员卡

            $order_gift_count = Db::name('order_mc_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->select()->toArray();

            if(!empty($order_gift_count)){

                foreach ($order_gift_count as $k => &$v){

                    $v['cat_name2'] = Db::name('single')->where('id',$v['single_content'])->value('cat_name');

                }

            }



            $now_gift_count = Db::name('order_mc_count')

                ->alias('ogc')

                ->join('single s','ogc.single_id = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.gift_count','gt',0)

                ->group('ogc.single_id')

                ->select()->toArray();//剩余次数大于0的礼包记录数 默认礼包分类

            if(empty($now_gift_count)){

                $now_gift_count[0]['single_id'] = '';

            }



            $single_id_array = Db::name('order_mc_count')

                ->alias('ogc')

                ->join('single s','ogc.single_content = s.id')

                ->where('order_id',$param['id'])

                ->where('ogc.single_id',$now_gift_count[0]['single_id'])

                // ->whereTime('end_time','>=',time())

                ->where('ogc.gift_count','gt',0)

                ->column('ogc.single_content');//剩余次数大于0的礼包记录数 默认礼包分类

        }





        if(!empty($now_gift_count)){

            foreach ($now_gift_count as $k => &$v){ //默认第一个门店的服务类人员金额

                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['single_id'])->value('person_price');

                if(is_null($person_price)) $person_price = '0.00';

                $v['person_price'] =  $person_price; //好像没啥用

                //$single_id_array[] = $v['single_content'];



            }

        }



        if(session('role_id') != 1){

            $info['username'] = hideStr($info['username'],1,6);

        }



        if(!empty($now_gift_count)){

            $service_people_price2 = Db::name('shop_service_price')

                ->alias('ssp')

                ->join('single s','ssp.single_id = s.id','right')

                ->where('shop_id',$shop_id)

                ->where('s.id','in',$single_id_array)

                ->where('auding_status',2)

                ->where('is_delete',1)

                ->field('s.id,s.cat_name,ssp.person_price')

                ->select(); //服务人员提成;

            $service_people_price3 = Db::name('shop_service_price')

                ->alias('ssp')

                ->join('single s','ssp.single_id = s.id','right')

                ->where('shop_id',$shop_id)

                ->where('s.parent_id','eq',$now_gift_count[0]['single_id'])

                ->where('auding_status',2)

                ->where('is_delete',1)

                ->field('s.id,s.cat_name,ssp.person_price')

                ->select(); //服务人员提成;

        }else{

            halt('else');

            $service_people_price2 = $service_people_price3 = '';

        }

        if($info['t_type'] == 1){

            if($service_people_price2->isEmpty()){

                fail('联系总台设置人员提成');

            }

        }

        $template = '';

        if(isset($param['table'])) $template = 'service_order_table';

        $info['cat_name'] = $info['gift_title'];

        $info['one_cat'] = '';



        return view($template, ['shop_list' => $shop_list,

            'item' => $info,

            'order_gift_count' => $order_gift_count,

            'now_gift_count' => json_encode($now_gift_count),

            'service_people_price2' => json_encode($service_people_price2),

            'service_people_price3' => json_encode($service_people_price3),

            'refund' => $refund,

            'shop_assignor' => $shop_assignor,

            'gift_assignor_records' => $shop_assignor_records,

            'shop_assignor_records' => $shop_assignor_records,

            'service_order_goods' => $service_order_goods,

            'refund_order_audit_records' => $refund_order_audit_records,

            'refund_button' => $refund_button,

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

        ]);

    }

    public function update_m(){



    }





    public function shop_assignor($shop_id){

        // 20200611

//        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->where('is_delete',1)->select();

        $shop_assignor = Db::name('shop_assignor')->where('is_delete',1)->select();

        return $shop_assignor;

    }



    /**

     * @param $order_id

     * @param $shop_id

     * @return string

     * ajax当前订单礼包 符合条件的服务类 以及服务金额

     */

    public function now_gift_count($order_id = 0,$shop_id = 0,$t_type = 1){

        //使用订单id查询当前订单的纪录礼包分类 然后根据门店获得价格

        if($t_type == 1){

            $table = 'order_gift_count';

        }

        if($t_type == 2){

            $table = 'order_mc_count';

        }

        $now_gift_count = Db::name($table)

            ->alias('ogc')

            ->join('single s','ogc.single_id = s.id')

            ->where('order_id',$order_id)

            ->where('ogc.gift_count','gt',0)

            ->whereTime('end_time','>=',time())

            ->group('ogc.single_id')

            ->select()->toArray();//剩余次数大于0的礼包记录数 //一级类

//        $now_gift_count2 = Db::name('single')

//            ->where('parent_id',$now_gift_count[0]['id'])

//            ->select()->toArray();

        $now_gift_count2 = Db::name($table)

            ->alias('ogc')

            ->join('single s','ogc.single_content = s.id')

            ->where('order_id',$order_id)

            ->where('ogc.gift_count','gt',0)

            ->whereTime('end_time','>=',time())

            ->where('single_id',$now_gift_count[0]['id'])

            ->select()->toArray();

        ;//剩余次数大于0的礼包记录数 //一级类

           ;//剩余次数大于0的礼包记录数 //一级类

        $gift_id = Db::name('order')->where('id',$order_id)->value('gift_id');

        if(!empty($now_gift_count2)){

            foreach ($now_gift_count2 as $k => &$v){ //默认第一个门店的服务类人员金额

                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['id'])->value('person_price');

                if(is_null($person_price)) $person_price = '0.00';

                $v['person_price'] =  $person_price;

                //$v['person_price'] =  $person_price+Db::name('gift_shop_price')->where('gift_id',$gift_id)->where('shop_id',$shop_id)->value('price');

            }

        }

        return ['one_level' => $now_gift_count,'two_level' => $now_gift_count2];



    }



    /**

     * @param $shop_id

     * @param $gift_id

     * @return int|mixed

     * ajax获取门店线下礼包金额

     */

    public function gift_shop_price($shop_id,$gift_id){

        $price = Db::name('gift_shop_price')->where(['shop_id' => $shop_id,'gift_id' => $gift_id])->value('price');

        if(is_null($price)) $price = 0;

        return $price;

    }





}